package co.com.ebusiness.trader.components;

import javax.servlet.http.HttpSession;

import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.Block;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.SymbolConstants;
import org.apache.tapestry5.annotations.Import;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.Symbol;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.RequestGlobals;
import org.apache.tapestry5.services.Session;

import co.com.ebusiness.trader.seguridad.model.UsuarioEmpresa;

/**
 * Layout component for pages of application trader.
 */
@Import(stylesheet = "context:layout/layout.css")
public class Layout
{
    /**
     * The page title, for the <title> element and the <h1> element.
     */
    @Property
    @Parameter(required = true, defaultPrefix = BindingConstants.LITERAL)
    private String title;

    @Property
    private String pageName;

    @Property
    @Parameter(defaultPrefix = BindingConstants.LITERAL)
    private String sidebarTitle;

    @Property
    @Parameter(defaultPrefix = BindingConstants.LITERAL)
    private Block sidebar;

    @Inject
    private ComponentResources resources;
    
    @Inject
    private RequestGlobals requestGlobals;
   
    @Persist
    @Property
    private String login;

    @Property
    @Inject
    @Symbol(SymbolConstants.APPLICATION_VERSION)
    private String appVersion;
    
    @Inject
 	private Request request;

 	
 	public boolean getHasSession() {
 		return request.getSession(false) != null;
 	}

 	public Session getSession() {
 		return request.getSession(false);
 	}

 	public String getNombreUsuario() {
 		String retString = null;
 		if (getSession() != null && getSession().getAttribute("state:Index::empresa") != null){
 			retString = ((UsuarioEmpresa)getSession().getAttribute("state:Index::empresa")).getUsuario().getNombre();
 		}
 		
 		return retString;
 	}


    public String getClassForPageName()
    {
        return resources.getPageName().equalsIgnoreCase(pageName)
                ? "current_page_item"
                : null;
    }

    public String[] getPageNames()
    {
        return new String[]{"Home", "About", "Contact"};
    }
    
    @OnEvent(component = "logout")
    public String onLogout()
    {
    	HttpSession session = requestGlobals.getHTTPServletRequest().getSession();
        session.invalidate();
        return "Index";

    }
}
